<?php
/**
 * 属性管理不作为单独管理，需要根据分类来编辑
 */
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Attribute;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class AttributeController extends Controller
{
    public function all(Request $request, $category)
    {
        $validator = $this->validate($category);
        if (!$validator) {
            return jsonResponse(40000);
        }

        $cat = $request->get('category');
        $items = Attribute::where('category_id', $cat)->get();
        return jsonResponse(config('common.successCode', $items));
    }

    public function create(Request $request, $category)
    {
        $validator = $this->validate($category);
        if (!$validator) {
            return jsonResponse(40000);
        }

        $cat = $request->get('category');
        $title = $request->get('title');
        $type = $request->get('type');

        $attr = new Attribute();
        $attr['category_id'] = $cat;
        $attr['title'] = $title;
        $attr['type'] = $type;
        // 2为选择输入
        if ($type == 2) {
            $value = $request->get('value');
            $attr['value'] = implode("|", $value);;
        }
        $attr->save();
        return jsonResponse();
    }

    public function update(Request $request, $category, $id)
    {
        $validator = $this->validate($category);
        if (!$validator) {
            return jsonResponse(40000);
        }

        $cat = $request->get('category');
        $title = $request->get('title');
        $type = $request->get('type');

        $attr = Attribute::find($id);
        if (empty($attr)) {
            return jsonResponse(40001);
        }
        $attr['category_id'] = $cat;
        $attr['title'] = $title;
        $attr['type'] = $type;
        // 2为选择输入
        if ($type == 2) {
            $value = $request->get('value');
            $attr['value'] = implode(config('common.delimiter'), $value);;
        }
        $attr->save();
        return jsonResponse();
    }

    public function destroy($category, $id)
    {
        Attribute::destroy($id);
        return jsonResponse();
    }

    private function validate($categoryId)
    {
        $category = Category::find($categoryId);
        if (empty($category)) {
            return false;
        }
        return true;
    }
}
